package fhb.mobile.manager.remoteDB;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.URL;

import fhb.mobile.manager.Storage;

import android.os.AsyncTask;
import android.widget.Toast;

public class LoginRemoteDB extends AsyncTask<String,String,String>{

	protected static final String servername = "10.0.2.2/android";
	
	@Override
	protected String doInBackground(String... params) {
		try {
			System.out.println("bla");
            URL fileUrl = new URL(getLoginRequest(params));
            fileUrl.openConnection().setConnectTimeout(30000);
            BufferedInputStream in = new BufferedInputStream(fileUrl.openStream());
            
            
            byte[] data = new byte[1024];
            int x;
            String response = "";

            while ((x = in.read(data, 0, 1024)) >= 0) {
                response = response + new String(data).substring(0, x);
            }

            in.close();
            return response;
        } catch (IOException ex) {
        	return "";
        }

	}
	
	protected void onPostExecute(String result){
		System.out.println(result);
		if (result.equals("")){
			Toast.makeText(Storage.getContext(), "Login into Server failed", 3000).show();
			Storage.setLogin(result);
		} else {
			if (result.equals("true")){
				Toast.makeText(Storage.getContext(), "Login success", 3000).show();
				Storage.setLogin(result);
			} else {
				System.out.println("test");
				Toast.makeText(Storage.getContext(), "Login into Server failed", 3000).show();
				Storage.setLogin(result);
			}
		}
	}
	
	private String getLoginRequest(String...strings ){
		
		String s ="http://" + servername + "/login.php?mail=" + strings[0] + "&pwhash=" + strings[1] ;
				
		return s;
	}

}
